<template>
  <div class="storeGroup-page">
    <div class="search-field">
      <el-form :model="searchForm" inline>
        <el-form-item label="区域名称" prop="name">
          <el-input
            placeholder="请输入区域名称"
            v-model="searchForm.name"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="上级区域" prop="parentId">
          <el-select
            style="width: 220px"
            v-model="searchForm.parentId"
            placeholder="选择上级区域"
          >
            <el-option
              v-for="option in storeGroupAllList"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>
            <el-button type="primary" @click="startSearch"> 查询 </el-button>
            <el-button @click="startClear"> 重置 </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-pagination-content">
      <div class="btns-fun-field">
        <!-- v-if="userPermission.addUserPerm" -->
        <el-button
          type="primary"
          @click.prevent="showAddEditDialog"
          :icon="Plus"
        >
          新增区域
        </el-button>
        <el-button
          type="primary"
          @click.prevent="showBatchLoadDialog"
          :icon="Plus"
        >
          批量导入门店区域
        </el-button>
      </div>
      <div class="table-field">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="tableLoading"
        >
          <el-table-column prop="number" label="编号" width="100" />
          <el-table-column prop="name" label="区域名称" width="160" />
          <el-table-column prop="parent_id" label="所属上级区域" width="160">
            <template #default="scope">
              <div>{{ scope.row.parentName || '全国' }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="门店数量" width="100">
            <template #default="scope">
              <div>{{ scope.row.amount || 0 }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="190" />
          <el-table-column label="操作" min-width="240px" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click.prevent="showAddEditDialog(scope.row, 1)"
                >添加子区域</el-button
              >
              <!-- v-if="rolePermission.editRolePerm" -->
              <el-button
                type="success"
                size="small"
                @click.prevent="showAddEditDialog(scope.row, 2)"
                >编辑</el-button
              >
              <!-- v-if="rolePermission.removeRolePerm" -->
              <el-button
                type="danger"
                size="small"
                @click.prevent="showRemoveDialog(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-field">
        <el-pagination
          v-model:current-page="formData.pageIndex"
          v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <StoreGroupAdd v-model="addUpdateRef"></StoreGroupAdd>
    <StoreGroupRemove v-model="removeRef"></StoreGroupRemove>
    <StoreGroupBatchLoad v-model="batchLoadRef"></StoreGroupBatchLoad>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  getStoreGroupPagination,
  getStoreGroupAllList,
  batchAddStoregroup,
} from '@/api/tms-store-group.api'
import { getStoreCategoryAllList } from '@/api/tms-store-category.api'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
// import { useUserPermission } from "@/utils/permission.utils";
import StoreGroupRemove from './component/StoreGroupRemove.vue'
import StoreGroupAdd from './component/StoreGroupAdd.vue'
import StoreGroupBatchLoad from './component/StoreGroupBatchLoad.vue'

import { getCanUseCode } from '@/api/fms-code-dict.api'

// const userPermission = useUserPermission();

/****
 * =============== 新增、修改相关操作 =====================
 */
const addUpdateRef = reactive({
  visible: false,
  disabled: false,
  title: `区域`,
  curSelectRow: {},
  storeCategoryList: [],
  storeGroupAllList: [],
  form: {},
  rules: {},
  refreshDataList: () => {
    getDataList()
    requestStoreGroupAllList()
  },
})

const requestCanUseCode = () => {
  getCanUseCode({ type: 8 })
    .then((res: any) => {
      console.log('getCanUseCode: ', res)
      addUpdateRef.form.number = res
    })
    .catch((err) => {
      ElMessage.error(err.msg)
    })
}

const showAddEditDialog = (item: any, type: number) => {
  if (type == null || type == 1) {
    addUpdateRef.type = 0
    let form = {
      id: null,
      number: '',
      name: '',
      level: '',
      mark: '',
      parentId: '',
    }

    if (type == 1) {
      form.parentId = item.id
      form.parentName = item.name
      form.level = item.level + 1
      addUpdateRef.type = 1
    }

    addUpdateRef.visible = true
    addUpdateRef.disabled = false
    addUpdateRef.form = form
    requestCanUseCode()
    return
  }

  let form = {
    id: item.id,
    number: item.number,
    name: item.name,
    level: item.level,
    parentId: item.parentId,
    mark: item.mark,
  }
  addUpdateRef.type = 2
  addUpdateRef.visible = true
  addUpdateRef.disabled = true
  addUpdateRef.form = form
}

//批量加入
const batchLoadRef = reactive({
  visible: false,
  title: `批量导入门店区域`,
  form: {},
  refreshDataList: () => {
    getDataList()
    requestStoreGroupAllList()
  },
})
const showBatchLoadDialog = () => {
  let form = {}
  batchLoadRef.visible = true
  batchLoadRef.form = form
}

/****
 * =============== 删除操作 =====================
 */
const removeRef = reactive({
  visible: false,
  title: '区域',
  curSelectRow: {},
  refreshDataList: () => {
    getDataList()
    requestStoreGroupAllList()
  },
})
const showRemoveDialog = (item: any) => {
  removeRef.visible = true
  removeRef.curSelectRow = item
}

/****
 * =============== 搜索、表格、分页 =====================
 */
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

const searchForm = ref({
  number: '',
  name: '',
  level: '',
  parentId: '',
  amount: '',
  mark: '',
  createBy: '',
  updateBy: '',
  createTime: '',
  updatedTime: '',
})

const tableLoading = ref(false)
const tableData = ref([])
/***
 * 开始搜索
 */
const startSearch = () => {
  formData.pageIndex = 1
  getDataList()
}

/***
 * 重置搜索条件
 */
const startClear = () => {
  formData.pageIndex = 1
  let value = searchForm.value
  Object.keys(value).forEach((key) => {
    ;(value as any)[key] = ''
  })
  getDataList()
}

const handleSizeChange = (value: number) => {
  formData.pageSize = value
  getDataList()
}

const handleCurrentChange = (value: number) => {
  formData.pageIndex = value
  getDataList()
}

const getDataList = () => {
  let searchCondition: any = {}

  let number = searchForm.value.number
  if (number) {
    searchCondition.number = number
  }
  let name = searchForm.value.name
  if (name) {
    searchCondition.name = name
  }
  let level = searchForm.value.level
  if (level) {
    searchCondition.level = level
  }
  let parentId = searchForm.value.parentId
  if (parentId !== undefined) {
    searchCondition.parentId = parentId
  }
  console.log('parentId: ', parentId)

  tableLoading.value = true
  getStoreGroupPagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
    ...searchCondition,
  })
    .then(function (res: any) {
      tableLoading.value = false
      console.log(res)
      tableData.value = res.list || []
      formData.total = Number(res.total)
    })
    .catch((error) => {
      console.log(error)
      tableLoading.value = false
    })
}

const storeCategoryList = ref([])
const requestStoreCategoryAllList = () => {
  getStoreCategoryAllList()
    .then((res) => {
      console.log('storeCategoryList: ', res)
      storeCategoryList.value = res || []
      addUpdateRef.storeCategoryList = storeCategoryList.value
    })
    .catch((err) => {
      console.log(err)
    })
}

const storeGroupAllList = ref([])
const requestStoreGroupAllList = () => {
  getStoreGroupAllList()
    .then((res) => {
      console.log('storeGroupAllList: ', res)
      res = res || []
      res = [
        {
          id: 0,
          name: '全国',
        },
        ...res,
      ]
      storeGroupAllList.value = res || []
      addUpdateRef.storeGroupAllList = storeGroupAllList.value
    })
    .catch((err) => {
      console.log(err)
    })
}

onMounted(() => {
  requestStoreCategoryAllList()
  requestStoreGroupAllList()
  getDataList()
})
</script>
<style lang="scss" scoped>
.storeGroup-page {
  height: 100%;
}

.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.btn-inner {
  display: flex;
  justify-content: center;
  color: #fff;
}

.tag-field {
  .el-tag {
    margin-right: 5px;
    &:last-child {
      margin-right: 0;
    }
  }
}

.search-field {
  margin-bottom: 12px;
  background: #fff;
  padding: 20px 20px 0px 20px;
  border-radius: 8px;
}

.storeGroup-page-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>
